package com.seeyon.apps.ext.cop.button.demo;

import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.event.*;
import com.seeyon.ctp.util.annotation.ListenEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import snail.common.utils.JSONHelper;
import snail.common.utils.MapHelper;
import snail.common.utils.db.DBHelper;
import snail.common.utils.db.DataSourceHelper;
import snail.common.web.HTTPHelper;

import javax.sql.DataSource;
import java.sql.SQLException;

import java.util.*;

public class EventListenersDemo {
    private final static Log LOG = LogFactory.getLog(EventListenersDemo.class);
    String key = "eb2abbcf-008d-4eea-ac66-ce105663519b";
    String url = "http://10.37.129.2:8989/selectDept";

    //正式数据源
    private static String urls = "jdbc:mysql://10.211.55.2:3306/cop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";// 连接URL字符串
    private static String user = "root";// 数据库用户名
    private static String password = "Mysql123456";// 用户密码



    @ListenEvent(event = DeleteDepartmentEvent.class, async = true)
    public void DeleteDepartmentEvent(DeleteDepartmentEvent event) throws BusinessException {
        System.out.println("删除部门事件");
        System.out.println("部门名称:" + event.getDept().getName().toString());// 部门名称
        System.out.println("部门编码:" + event.getDept().getCode().toString());// 部门编码
        System.out.println("部门创建id:" + event.getDept().getId());// 创建id
        System.out.println("部门主数据:" + event.getDept().getCustomerProperties());//
        System.out.println("部门经理:" + event.getDept().getDepManager());// 部门经理y
        System.out.println("部门说明:" + event.getDept().getDescription());// 说明
        System.out.println("部门类型:" + event.getDept().getEntityType());// 类型
        System.out.println("部门I18nNameId:" + event.getDept().getI18nNameId());
        System.out.println("部门IsGroup:" + event.getDept().getIsGroup());
        System.out.println("上级部门:" + event.getDept().getSuperiorName());// 上级部门
        System.out.println("上级部门:" + event.getDept().getSuperior());// 上级部门 Y
        System.out.println("组织帐户id:" + event.getDept().getOrgAccountId());// 所属单位ID
        System.out.println("组织帐户id:" + event.getDept().getPreName());// 组织帐户
        boolean Status = event.getDept().getEnabled();
        Long id = event.getDept().getId();
        List managerList = new ArrayList();
        for (Map<String, Object> userOas : selectDepManager(id)) {
            managerList.add(userOas.get("username"));
        }
        List leaderList = new ArrayList();
        for (Map<String, Object> userOas : selectDepLeader(id)) {
            leaderList.add(userOas.get("username"));
        }
        List assistantList = new ArrayList();
        for (Map<String, Object> userOas : selectDepAssistant(id)) {
            assistantList.add(userOas.get("username"));
        }

        String body = MapHelper.builder("deptId", String.valueOf(event.getDept().getId()))
                .put("deptName", String.valueOf(event.getDept().getName()))
                .put("superiorName", selectSuperiorName(event.getDept().getSuperior()))
                .put("depManagers", managerList)
                .put("depLeader", leaderList)
                .put("assistant", assistantList)
                .toJson();
        try {
            Map<String, Object> header = MapHelper.builder("Content-Type", "application/json").body();

            Map<String, Object> result = (Map<String, Object>) JSONHelper.parse(HTTPHelper.post(url, body, header));

            List<String> list = new ArrayList<>();

            list.add((String) result.get("id"));

            System.out.println(list);

            event.getDept().setCustomerProperties(list);

        } catch (Exception e) {
            LOG.error(e);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.print("resultString");
    }

    /**
     * 查找部门经理
     * @param id
     * @return
     */
    public List<Map<String, Object>> selectDepManager(Long id) {

        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(urls, user, password);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        List<Map<String, Object>> userList = new ArrayList<>();
        try {
            userList = dbhelper.queryList("select a.name deptName,a.PATH,a.ID,b.OBJECTIVE1_ID,d.name username,c.name postName from ORG_UNIT a left join ORG_RELATIONSHIP b on \n" +
                    "a.id = b.OBJECTIVE0_ID left join org_role c on b.OBJECTIVE1_ID = c.id left join ORG_MEMBER d\n" +
                    "on b.source_id = d.id where  c.code = 'DepManager' and a.id = ?", id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userList;
    }
    /**
     * 查找部门主管
     * @param id
     * @return
     */
    public List<Map<String, Object>> selectDepLeader(Long id) {

        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(urls, user, password);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        List<Map<String, Object>> userList = new ArrayList<>();
        try {
            userList = dbhelper.queryList("select a.name deptName,a.PATH,a.ID,b.OBJECTIVE1_ID,d.name username,c.name postName from ORG_UNIT a left join ORG_RELATIONSHIP b on \n" +
                    "a.id = b.OBJECTIVE0_ID left join org_role c on b.OBJECTIVE1_ID = c.id left join ORG_MEMBER d\n" +
                    "on b.source_id = d.id where  c.code = 'DepLeader' and a.id = ?", id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userList;
    }
    /**
     * 查找部门助理
     * @param id
     * @return
     */
    public List<Map<String, Object>> selectDepAssistant(Long id) {

        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(urls, user, password);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        List<Map<String, Object>> userList = new ArrayList<>();
        try {
            userList = dbhelper.queryList("select a.name deptName,a.PATH,a.ID,b.OBJECTIVE1_ID,d.name username,c.name postName from ORG_UNIT a left join ORG_RELATIONSHIP b on \n" +
                    "a.id = b.OBJECTIVE0_ID left join org_role c on b.OBJECTIVE1_ID = c.id left join ORG_MEMBER d\n" +
                    "on b.source_id = d.id where  c.code = 'DepAssistant' and a.id = ?", id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return userList;
    }

    /**
     * 查找上级部门
     * @param id
     * @return
     */
    public String selectSuperiorName(Long id) {

        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(urls, user, password);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        try {
            return dbhelper.queryString("select name from org_unit where id = ?", id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


    @ListenEvent(event = AddDepartmentEvent.class, async = true)
    public void AddDepartmentEvent(AddDepartmentEvent event) throws BusinessException {
        System.out.println("新增部门事件");
        System.out.println("部门名称:" + event.getDept().getName().toString());// 部门名称
        System.out.println("部门编码:" + event.getDept().getCode().toString());// 部门编码
        System.out.println("部门创建id:" + event.getDept().getId());// 创建id
        System.out.println("部门主数据:" + event.getDept().getCustomerProperties());//
        System.out.println("部门经理:" + event.getDept().getDepManager());// 部门经理y
        System.out.println("部门说明:" + event.getDept().getDescription());// 说明
        System.out.println("部门类型:" + event.getDept().getEntityType());// 类型
        System.out.println("部门I18nNameId:" + event.getDept().getI18nNameId());
        System.out.println("部门IsGroup:" + event.getDept().getIsGroup());
        System.out.println("上级部门:" + event.getDept().getSuperiorName());// 上级部门
        System.out.println("上级部门:" + event.getDept().getSuperior());// 上级部门 Y
        System.out.println("组织帐户id:" + event.getDept().getOrgAccountId());// 组织帐户
        System.out.println("组织帐户id:" + event.getDept().getPreName());// 组织帐户 Y
        System.out.println("部门状态:" + event.getDept().getEnabled());// 部门状态 Y

        Long id = event.getDept().getId();
        List managerList = new ArrayList();
        for (Map<String, Object> userOas : selectDepManager(id)) {
            managerList.add(userOas.get("username"));
        }
        List leaderList = new ArrayList();
        for (Map<String, Object> userOas : selectDepLeader(id)) {
            leaderList.add(userOas.get("username"));
        }
        List assistantList = new ArrayList();
        for (Map<String, Object> userOas : selectDepAssistant(id)) {
            assistantList.add(userOas.get("username"));
        }


        String body = MapHelper.builder("deptId", String.valueOf(event.getDept().getId()))
                .put("deptName", String.valueOf(event.getDept().getName()))
                .put("superiorName", selectSuperiorName(event.getDept().getSuperior()))
                .put("depManagers", managerList)
                .put("depLeader", leaderList)
                .put("assistant", assistantList)
                .toJson();
        try {
            Map<String, Object> header = MapHelper.builder("Content-Type", "application/json").body();

            Map<String, Object> result = (Map<String, Object>) JSONHelper.parse(HTTPHelper.post(url, body, header));

            List<String> list = new ArrayList<>();

            list.add((String) result.get("id"));

            System.out.println(list);

            event.getDept().setCustomerProperties(list);

        } catch (Exception e) {
            LOG.error(e);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.print("resultString");
    }

    
    @ListenEvent(event = UpdateDepartmentEvent.class, async = true)
    public void UpdateDepartmentEvent(UpdateDepartmentEvent event) throws BusinessException {
        System.out.println("部门修改事件");
        System.out.println("部门名称:" + event.getDept().getName().toString());// 部门名称
        System.out.println("部门编码:" + event.getDept().getCode().toString());// 部门编码
        System.out.println("部门创建id:" + event.getDept().getId());// 创建id
        System.out.println("部门主数据:" + event.getDept().getCustomerProperties());//
        System.out.println("部门经理:" + event.getDept().getDepManager());// 部门经理y
        System.out.println("部门说明:" + event.getDept().getDescription());// 说明
        System.out.println("部门类型:" + event.getDept().getEntityType());// 类型
        System.out.println("部门I18nNameId:" + event.getDept().getI18nNameId());
        System.out.println("部门IsGroup:" + event.getDept().getIsGroup());
        System.out.println("上级部门:" + event.getDept().getSuperiorName());// 上级部门
        System.out.println("上级部门:" + event.getDept().getSuperior());// 上级部门 Y
        System.out.println("组织帐户id:" + event.getDept().getOrgAccountId());// 组织帐户
        System.out.println("部门状态:" + event.getDept().getEnabled());// 部门状态 Y
        Long id = event.getDept().getId();
        List managerList = new ArrayList();
        for (Map<String, Object> userOas : selectDepManager(id)) {
            managerList.add(userOas.get("username"));
        }
        List leaderList = new ArrayList();
        for (Map<String, Object> userOas : selectDepLeader(id)) {
            leaderList.add(userOas.get("username"));
        }
        List assistantList = new ArrayList();
        for (Map<String, Object> userOas : selectDepAssistant(id)) {
            assistantList.add(userOas.get("username"));
        }


        String body = MapHelper.builder("deptId", String.valueOf(event.getDept().getId()))
                .put("deptName", String.valueOf(event.getDept().getName()))
                .put("superiorName", selectSuperiorName(event.getDept().getSuperior()))
                .put("depManagers", managerList)
                .put("depLeader", leaderList)
                .put("assistant", assistantList)
                .toJson();
        try {
            Map<String, Object> header = MapHelper.builder("Content-Type", "application/json").body();

            Map<String, Object> result = (Map<String, Object>) JSONHelper.parse(HTTPHelper.post(url, body, header));

            List<String> list = new ArrayList<>();

            list.add((String) result.get("id"));

            System.out.println(list);
            event.getDept().setDescription("哇哎琦琦");
            event.getDept().setCustomerProperties(list);


        } catch (Exception e) {
            LOG.error(e);
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.print("resultString");

    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrls() {
        return urls;
    }

    public void setUrls(String urls) {
        this.urls = urls;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
